<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
    >
      <el-form-item
          label-width="auto"
          :label="$t('productTemplate')"
          prop="protypeId"
      >
        <el-input
            v-model="queryParams.protypeId"
            :placeholder="$t('pleaseEnterTheProductTemplateType')"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
        >{{ $t("search") }}
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
            $t("reset")
          }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:typetemplate:add']"
        >{{ $t("add") }}
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:typetemplate:edit']"
        >{{ $t("edit") }}
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:typetemplate:remove']"
        >{{ $t("delete") }}
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleInheritance"
            v-hasPermi="['system:typetemplate:edit']"
        >{{ $t("copy") }}
        </el-button
        >
      </el-col>
      <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="typetemplateList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
          :label="$t('productTemplateType')"
          align="center"
          prop="remark"
      />

      <el-table-column
          :label="$t('controls')"
          align="center"
          class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:typetemplate:edit']"
          >{{ $t("edit") }}
          </el-button
          >
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:typetemplate:remove']"
          >{{ $t("delete") }}
          </el-button
          >

          <el-button
              size="mini"
              type="text"
              icon="el-icon-clear"
              @click="orderBy(scope.row)"
              v-hasPermi="['system:typetemplate:edit']"
          >{{ $t("sort") }}
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改产品类型模板对话框 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="600px"
        append-to-body
        center
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <!--        <el-form-item label="产品类别:" prop="protypeId">-->
        <!--          <el-select v-model="form.protypeId" placeholder="请输入产品类型">-->
        <!--            <el-option v-for="dict in productTypes" :key="dict.productId" :label="dict.productName"-->
        <!--              :value="dict.productId"></el-option>-->
        <!--          </el-select>-->

        <!--        </el-form-item>-->
        <el-form-item :label="$t('productCategory')" prop="protypeId">
          <treeselect
              :disabled="this.isAdd == 1"
              style="width: 218px"
              v-model="form.protypeId"
              :normalizer="normalizer"
              :options="protypeOptions"
              :placeholder="$t('pleaseSelectPublicAttribute')"
          />
        </el-form-item>
        <el-form-item
            :label="$t('basicAttributeCategory')"
            prop="basicattributeIds"
        >
          <el-select
              v-model="form.basicattributeIds"
              :placeholder="$t('pleaseSelectBasicAttribute')"
              multiple
          >
            <el-option
                v-for="dict in basicattributes"
                :key="dict.basicattributeId"
                :label="dict.basicattributeLabel"
                :value="dict.basicattributeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('publicAttribute')" prop="publicattributeIds">
          <el-tree
              :default-expand-all="true"
              :data="typeOptions"
              :props="defaultProps"
              ref="tree"
              show-checkbox
              check-strictly
              :expand-on-click-node="false"
              node-key="publicattributeId"
              check-on-click-node
              @check-change="handleNodeClick"
          ></el-tree>
          <!--          <el-select v-model="value" multiple placeholder="请选择" :popper-append-to-body="false" @remove-tag="removetag"-->
          <!--            @clear="clearall" clearable>-->
          <!--            <el-option :value="selectTree" class="setstyle" disabled>-->
          <!--              <el-tree :data="typeOptions" :props="defaultProps" ref="tree" show-checkbox check-strictly-->
          <!--                :expand-on-click-node="false" node-key="publicattributeId" check-on-click-node-->
          <!--                @check-change="handleNodeClick"></el-tree>-->
          <!--            </el-option>-->
          <!--          </el-select>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("ok") }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
        :title="$t('sort')"
        :visible.sync="open2"
        width="900px"
        append-to-body
        center
    >
      <el-form
          :model="formSort"
          ref="formSort"
          label-width="400px"
          class="demo-dynamic"
      >
        <el-form-item
            v-for="(domain, index) in this.orderVo"
            :label="domain.name"
            :key="domain.id"
            :prop="'publicattributeOrder.' + index + '.orderNum'"
        >
          <el-input-number
              v-model="domain.orderNum"
              controls-position="right"
              :min="1"
              :max="99"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSort">{{
            $t("ok")
          }}
        </el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTypetemplate,
  getTypetemplate,
  delTypetemplate,
  addTypetemplate,
  updateTypetemplate,
  typetemplateList,
  getTypetemplateOrder,
  updateTypetemplateOrder,
} from "@/api/system/typetemplate";
import {listType, listTypete} from "@/api/system/publicattributeType";

import {listProtype} from "@/api/system/protype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Typetemplate",
  components: {Treeselect},
  data() {
    return {
      protypeOptions: [],
      value: [],
      selectTree: [],
      defaultProps: {
        children: "children",
        label: "publicattributeName",
      },
      typeOptions: [],
      basicattributes: [],
      publicattributes: [],
      productTypes: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      isAdd: 0,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      types: [],
      orderVo: [],
      // 产品类型模板表格数据
      typetemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        protypeId: null

      },
      // 表单参数
      form: {},
      formSort: {},
      // 表单校验
      rules: {
        protypeId: [
          {
            required: true,
            message: this.$t("basicCa"),
            trigger: "blur",
          },
        ],
          basicattributeIds: [
          {
            required: true,
            message: this.$t("basicCa"),
            trigger: "blur",
          },
        ],
          publicattributeIds: [
              {
                  required: true,
                  message: this.$t("basicCa"),
                  trigger: "blur",
              },
          ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.productId,
        label: node.remark,
        children: node.children,
      };
    },

    submitFormSort() {
      this.$refs["formSort"].validate((valid) => {
        console.log(this.orderVo);
        updateTypetemplateOrder(this.orderVo).then((this.open2 = false));
      });
    },
    getTreeselectProductTyps() {
      listProtype().then((response) => {
        this.protypeOptions = [];
        const data = {
          productId: 0,
          remark: this.$t("top-node"),
          children: [],
        };
        data.children = this.handleTree(response.data, "productId", "parentId");
        this.protypeOptions.push(data);
      });
    },
    /** 查询产品共有属性类型下拉树结构 */
    getTreeselect() {
      listTypete().then((response) => {
        this.typeOptions = [];
        this.types = response.data;

        const data = {
          publicattributeId: 0,
          publicattributeName: this.$t("top-node"),
          children: [],
          disabled: true,
        };
        data.children = this.handleTree(
            response.data,
            "publicattributeId",
            "parentId"
        );
        console.log(data)
        this.typeOptions.push(data);
        this.typeOptions.forEach((item) => {

          item.children.forEach((child) => {

            if (child.parentId == 0) child.disabled = true;
          });
        });
      });
    },
    // 树形选择框方法
    handleNodeClick(data, self, child) {
      console.log(this.$refs.tree.getCheckedNodes());
      let datalist = this.$refs.tree.getCheckedNodes();
      this.selectTree = []; //置空
      this.value = [];
      datalist.forEach((item) => {
        this.selectTree.push({
          id: item.publicattributeId,
          label: item.publicattributeName,
        });
        this.value.push(item.publicattributeName);
      });
    },
    removetag() {
      this.selectTree.splice(0, 1);
      let setlist = this.$refs.tree.getCheckedNodes();
      setlist.splice(0, 1);
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(setlist);
      });
    },
    clearall() {
      this.selectTree = [];
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes([]);
      });
    },
    /** 查询产品类型模板列表 */
    getList() {
      this.loading = true;
      listTypetemplate(this.queryParams).then((response) => {
        this.typetemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getTreeselect();
      this.getTreeselectProductTyps();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        protypeId: null,
        basicattributeIds: [],
        basicattributeNames: [],
        basicattributeOrder: [],
        publicattributeIds: [],
        publicattributeNames: [],
        publicattributeOrder: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.protypeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // order() {
    //   this.form.basicattributeOrder=[]
    //   this.form.publicattributeOrder=[]
    //   for(let i=0;i<this.form.basicattributeIds.length;i++) {
    //     var items = {id: this.form.basicattributeIds[i], value: 0}
    //
    //     this.basicattributes.forEach(
    //       (item) => {
    //         if (item.basicattributeId == this.form.basicattributeIds[i]) {
    //           items["name"] = item.basicattributeLabel
    //         }
    //       }
    //     )
    //     this.form.basicattributeOrder.push(items)
    //   }
    //
    //  for(let i=0;i<this.form.publicattributeIds.length;i++){
    //    var items ={ id: this.form.publicattributeIds[i],value: 0}
    //
    //    this.types.forEach(
    //      (item) => {
    //        if(item.publicattributeId==this.form.publicattributeIds[i]){
    //          items["name"]=item.publicattributeName
    //        }
    //      }
    //    )
    //    this.form.publicattributeOrder.push(items)
    //    console.log(items)
    //  }
    //
    //
    //   this.open2 = true;
    //
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isAdd = 0;
      this.getTreeselectProductTyps();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
      typetemplateList().then((response) => {
        this.productTypes = response.MenuProtypeList;
        this.basicattributes = response.MenuProductBasicattributeList;
      });
      this.open = true;
      this.title = this.$t("addProductCategoryTemplate");
    },
    orderBy(row) {
      this.orderVo = [];
      getTypetemplateOrder(row.protypeId).then((response) => {
        this.orderVo = response.orderVos;
      });
      this.open2 = true;
    },
    /*继承模版*/
    handleInheritance(row) {
      this.reset();
      this.isAdd = 0;
      this.getTreeselectProductTyps();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });

      const protypeId = row.protypeId || this.ids;
      typetemplateList().then((response) => {
        this.productTypes = response.MenuProtypeList;
        this.basicattributes = response.MenuProductBasicattributeList;
      });

      getTypetemplate(protypeId).then((response) => {
        this.$set(this.form, "protypeId", response.protypeId);
        this.$set(this.form, "basicattributeIds", response.basicattributeIds);
        this.value = response.publicattributeIds;
        const roleMenu = response.publicattributeIds;

        this.$nextTick(() => {
          roleMenu.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.tree.setChecked(v, true, false);
            });
          });
        });
        this.open = true;
        this.title = this.$t("copy1");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isAdd = 1;
      this.getTreeselectProductTyps();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });

      const protypeId = row.protypeId || this.ids;
      typetemplateList().then((response) => {
        this.productTypes = response.MenuProtypeList;
        this.basicattributes = response.MenuProductBasicattributeList;
      });

      getTypetemplate(protypeId).then((response) => {
        this.$set(this.form, "protypeId", protypeId);
        this.$set(this.form, "basicattributeIds", response.basicattributeIds);
        this.value = response.publicattributeIds;
        const roleMenu = response.publicattributeIds;

        this.$nextTick(() => {
          roleMenu.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.tree.setChecked(v, true, false);
            });
          });
        });
        this.open = true;
        this.title = this.$t("alterProductCategoryTemplate");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.isAdd == 1) {
            if (this.form.protypeId == null) {
              return this.$modal.msgError(
                  this.$t("pleaseSelectAProductCategory")
              );
            }
            updateTypetemplate(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("modifiedSuccessfully"));
              this.open = false;
              this.open2 = false;
              this.getList();
            });
          } else {
            if (this.form.protypeId == null) {
              return this.$modal.msgError(
                  this.$t("pleaseSelectAProductCategory")
              );
            }
            addTypetemplate(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("newSuccessfullyAdded"));
              this.open = false;
              this.open2 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const protypeIds = row.protypeId || this.ids;
      this.$modal
          .confirm(
              this.$t("areYouSureYouWantToDeleteTheDataItemWithTypeNumber")

          )
          .then(function () {
            return delTypetemplate(protypeIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess(this.$t("deleteSuccessfully"));
          })
          .catch(() => {
          });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
          "system/typetemplate/export",
          {
            ...this.queryParams,
          },
          `typetemplate_${new Date().getTime()}.xlsx`
      );
    },
  },
  watch: {
    selectTree: {
      handler(newValue) {
        this.form.publicattributeIds = newValue.map((item) => item.id);
      },
      deep: true,
    },
  },
};
</script>
<style scoped>
.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}
</style>
